# import sys
import flask,json
# print(sys.path)
from main.link.dbLink import dbLink
from test.sql.sqlDelete import sqlDelete
from test.sql.sqlSelect import sqlSelect
from test.sql.sqlUpdate import sqlUpdate

def after_request(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type,Authorization'
    return response

#函    数：执行SQL命令，预览命令结果
#前    提：
#参    数：action(数字类型) SQL语句动作，tableName(字符类型) 数据表名称，condition(字符类型) where后面的具体条件
#请求格式：curl -X POST http://127.0.0.1:8888/jaina?go=backupPhone
#返回结果：{'msg':'新备份了2个文件!重新备份了10个文件!共有备份文件100个!','msg_code':200}

apiSQL = flask.Flask(__name__)

#消除浏览器 提示：Access to XMLHttpRequest at 'http://127.0.0.1:8888/jaina' from origin 'http://localhost:63342' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
apiSQL.after_request(after_request)


@apiSQL.route('/jaina',methods=['post'])
def goSQL():
    # 参数
    go = flask.request.values.get('go')

    if go == "sqlTool":
        #连接数据库
        dbDatabase = 'mysql'
        db = dbLink('114.115.248.128','root','Esxi0000.',dbDatabase);
        # cursor = db.cursor()

        # 参数
        #drop=0 select=1 update=2 insert=3 delete=4
        action = flask.request.values.get('action')

        #tableName tableName="user"
        tableName = flask.request.values.get('tableName')
        #condition 条件 username="wuxk"
        condition = flask.request.values.get('condition')
        #确认执行 =ok
        verify = flask.request.values.get('verify')

        #derBug
        # print("derBug POST Parameter: " + "go=" + go + ",action=" + action + ",tableName=" + tableName + ",condition=[" + condition + "]" + ",verify=" + verify)

        if action == '0':
            result = {'msg':'drop','msg_code':200}
            print(result)
        elif action == '1':
            # 查询的字段
            col = flask.request.values.get('col')
            ren = sqlSelect(db,dbDatabase,tableName,condition,col)
        elif action == '2':
            result = {'msg':'update','msg_code':200}
            print(result)
        elif action == '3':
            ren = sqlUpdate(db,dbDatabase,tableName,condition,verify)
        elif action == '4':
            ren = sqlDelete(db,dbDatabase,tableName,condition,verify)
    else:
         ren = {'msg':'你在狗叫什么!FUCK!','msg_code':200}

    print("derBug Return Result: " + str(ren))

    #接口的返回值
    return json.dumps(ren,ensure_ascii=False)

if __name__ == '__main__':
    apiSQL.run(port=3333,debug=True,host='127.0.0.1')